package org.zht.dormpro.auth.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.NonNull;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zht.dormpro.auth.bean.PageBean;
import org.zht.dormpro.auth.bean.Tree;
import org.zht.dormpro.pub.constant.Enums;
import org.zht.dormpro.auth.mapper.SysPermissionMapper;
import org.zht.dormpro.auth.mapper.SysUserMapper;
import org.zht.dormpro.auth.mapper.SysUserRoleMapper;
import org.zht.dormpro.auth.model.SysPermission;
import org.zht.dormpro.auth.model.SysUser;
import org.zht.dormpro.auth.model.SysUserRole;
import org.zht.dormpro.auth.service.ISysUserService;
import org.zht.dormpro.pub.util.BuildTree;
import org.zht.dormpro.pub.util.MD5HashUtil;
import org.zht.dormpro.pub.util.ShiroUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public SysUser getSysUserByUsercode(String id) {
        return sysUserMapper.getSysUserByUserCode(id);
    }

    @Override
    public List<Tree<SysPermission>> getUserMenuTree(Integer userId) {
        List<SysPermission> menus = null;
        //最高权限
        if (userId == 0) {
            menus = sysPermissionMapper.getAllMenuTree(null);
        } else {
            menus = sysPermissionMapper.getUserMenuTree(userId);
        }
        List<Tree<SysPermission>> trees = new ArrayList<>();
        List<Tree<SysPermission>> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(menus)) {
            for (SysPermission menu : menus) {
                if(menu.getType()==1){
                    continue;
                }
                Tree<SysPermission> tree = new Tree<>();
                tree.setId(menu.getId());
                tree.setText(menu.getName());
                tree.setParentId(menu.getParentId());
                Map<String, Object> attrbutes = new HashMap<>();
                attrbutes.put("icon", menu.getIcon());
                attrbutes.put("url", menu.getUrl());
                tree.setAttributes(attrbutes);
                trees.add(tree);
            }
            //排序
            list = BuildTree.buildTreeList(trees, 0);
        }
        return list;
    }

    @Override
    public List<SysUser> getUserByCondition(PageBean pageBean) {
        Page<Object> objects = PageHelper.startPage(pageBean.getPageNum(), pageBean.getLimit());
        List<SysUser> sysUsers = sysUserMapper.selectByCondition(pageBean);
        pageBean.setTotal((int) objects.getTotal());
        return sysUsers;
    }

    @Override
    public Integer addUser(SysUser sysUser) {
        sysUser.setSalt(sysUser.getUsercode());
        sysUser.setMender(ShiroUtil.getAuthUser().getUserId());
        sysUser.setCreator(ShiroUtil.getAuthUser().getUserId());
        sysUser.setModifyTime(System.currentTimeMillis());
        sysUser.setCreateTime(System.currentTimeMillis());
        sysUser.setPassword(MD5HashUtil.getPassword(sysUser.getPassword(), sysUser.getSalt(), 2));
        int id = sysUserMapper.insertSelective(sysUser);
        return id > 0 ? sysUser.getId() : 0;
    }

    @Override
    public List<SysPermission> getPermissionListById(Integer userid) {
        return sysPermissionMapper.getUserPermissionByUid(userid);
    }

    @Override
    public boolean deleteUserRoRL(Integer id, @NonNull Enums.URStatus urStatus) {
        int count = userRoleMapper.deleteUserRoRL(id, urStatus.toString());
        return count >= 0;
    }

    @Override
    public List<SysUserRole> getUserRoRL(Integer id, Enums.URStatus urStatus) {
        List<SysUserRole> sysUserRoles = userRoleMapper.getUserRoRL(id, urStatus.toString());
        return sysUserRoles;
    }

    @Override
    public boolean addRoleUserRL(ArrayList<String> strings, Integer id) {
        if (CollectionUtil.isNotEmpty(strings)) {
            SysUserRole sysUserRole = null;
            for (String string : strings) {
                if(StrUtil.isNotBlank(string)){
                    sysUserRole = new SysUserRole();
                    sysUserRole.setCreateTime(System.currentTimeMillis());
                    sysUserRole.setCreator(ShiroUtil.getAuthUser().getUserId());
                    sysUserRole.setMender(ShiroUtil.getAuthUser().getUserId());
                    sysUserRole.setModifyTime(System.currentTimeMillis());
                    sysUserRole.setSysRoleId(Integer.valueOf(string));
                    sysUserRole.setSysUserId(id);
                    int i = userRoleMapper.insertSelective(sysUserRole);
                    if (i <= 0) {
                        return false;
                    }
                }
            }
            return true;
        }
        return true;
    }

    @Override
    public boolean deleteUser(Integer id) {
        return sysUserMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public SysUser getSysUserById(Integer id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean update(SysUser sysUser) {
        sysUser.setMender(ShiroUtil.getAuthUser().getUserId());
        sysUser.setModifyTime(System.currentTimeMillis());
        int i = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        return i > 0;
    }

    @Override
    public boolean updateUserRoleRL(ArrayList<String> strings, Integer id) {
        //移除所有的
        List<SysUserRole> userRoRL = getUserRoRL(id, Enums.URStatus.USER);
        if (CollectionUtil.isNotEmpty(userRoRL)) {
            boolean b = deleteUserRoRL(id, Enums.URStatus.USER);
        }
        //添加
        boolean b = addRoleUserRL(strings, id);

        return b;
    }

    @Override
    public boolean resetPassword(Integer id,String password) {
        //查询用户
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(id);
        if(sysUser!=null){
            String realPwd = MD5HashUtil.getPassword(password, sysUser.getSalt(), 2);
            Long count = sysUserMapper.resetPassword(id,realPwd);
            return count>0;
        }
        return false;
    }
}
